import 'dart:io';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart' as imagePicker;
import 'package:permission_handler/permission_handler.dart';

class ImagePicker {
  static Future<File> pickImage(BuildContext context) async {
    var result = await showCupertinoModalPopup<imagePicker.ImageSource>(
        context: context,
        builder: (context) {
          return CupertinoActionSheet(
              actions: <Widget>[
                CupertinoActionSheetAction(
                  child: Text('拍照'),
                  onPressed: () {
                    Navigator.pop(context, imagePicker.ImageSource.camera);
                  },
                ),
                CupertinoActionSheetAction(
                  child: Text('从手机相册选择'),
                  onPressed: () {
                    Navigator.pop(context, imagePicker.ImageSource.gallery);
                  },
                ),
              ],
              cancelButton: CupertinoActionSheetAction(
                child: Text('取消'),
                onPressed: () {
                  Navigator.pop(context);
                },
              ));
        });

    if (result != null) {
      final permission = result == imagePicker.ImageSource.gallery ? Permission.photos : Permission.camera;

      final status = await PermissionUtil.checkPermission(
        permission,
      );

      if (status) {
        return await _pickImage(context, result);
      } else {
        toast('该权限已经被禁止了，请前往设置开启该权限');
        return null;
      }
    }

    return null;
  }

  static Future<File> _pickImage(BuildContext context, source) async {
    return await imagePicker.ImagePicker.pickImage(source: source);
  }
}
